#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File   ：FastRiteApi -> get_auth_code
@IDE    ：PyCharm
@Author ：Json
@Date   ：2025/3/20 11:09
@Desc   ：
=================================================='''

import json
import hmac
import hashlib
from collections import OrderedDict


def generate_authcode(app_key: str, app_secret: str, req_time: int, data: dict) -> str:
    """
    生成认证签名authcode

    :param app_key: 应用密钥ID
    :param app_secret: 应用密钥
    :param req_time: 10位UNIX时间戳
    :param data: 业务数据字典
    :return: HMAC-SHA256签名字符串
    """
    # 1. 处理data数据排序
    sorted_data = _sort_data(data)

    # 2. 构造签名参数集
    sign_params = OrderedDict()
    sign_params["appKey"] = app_key
    sign_params["data"] = sorted_data
    sign_params["reqTime"] = str(req_time)

    # 3. 按参数名不区分大小写排序
    sorted_keys = sorted(sign_params.keys(), key=lambda k: k.lower())

    # 4. 拼接参数值
    sign_str = "".join([sign_params[key] for key in sorted_keys])

    # 5. HMAC-SHA256加密
    return _hmac_sha256(sign_str, app_secret)


def _sort_data(data) -> str:
    """处理data字典排序并生成紧凑JSON字符串"""
    # 按key不区分大小写排序
    if isinstance(data,dict):
        sorted_keys = sorted(data.keys(), key=lambda k: k.lower())
        # 生成有序字典
        sorted_data = {k: data[k] for k in sorted_keys}
    else:
        sorted_data = data

    # 生成无空格紧凑JSON
    return json.dumps(sorted_data, separators=(",", ":"))


def _hmac_sha256(message: str, secret: str) -> str:
    """HMAC-SHA256加密"""
    digest = hmac.new(
        secret.encode("utf-8"),
        message.encode("utf-8"),
        hashlib.sha256
    )
    return digest.hexdigest()


# 使用示例
if __name__ == "__main__":
    app_key = "xxxx"
    app_secret = "xxxxx"
    req_time = 1653640516
    # data = {
    #     "current": 1,
    #     "size": 10,
    #     "outboundOrderNos": "OB069220519008,OB069220519007,OB069220519006"
    # }
    data = [{
        "sku": "BM-DET400G01",
        "productCode": "732416595398",
        "productName": "Educator ET-400 Transmitters battery",
        "length": 7,
        "width": 5,
        "height": 2,
        "weight": 0.04,
        "declareNameCn": "Educator ET-400 Transmitters 电池",
        "declareNameEn": "Educator ET-400 Transmitters battery",
        # "customhouseCode": "HS1234.56.78",
        "declarePrice": 1,
        "countryOfOriginName": "CN",
        "dangerousCargo": 4,
        # 可选字段示例
        "productAliasName": "ET-400 battery",
    }]

    authcode = generate_authcode(app_key, app_secret, req_time, data)
    print(f"生成的authcode: {authcode}")
    # 应输出: 31450e8c7603b1b2a4fdb0143740a105d7260cb291c08208b658eabe52f1ec6b
    # f609c493faebc36fabb4a8ba183763ab503820f1475d2942ce79546293cf0f65
    # f609c493faebc36fabb4a8ba183763ab503820f1475d2942ce79546293cf0f65
